define(['config', 'util/storage'], (config, util) => {
    const origin = config.network.origin;

    function CreateUrl() {}

    Object.assign(CreateUrl.prototype, {

        /**
         * 创建 请求 URL
         * @param url
         * @param options
         * @returns {string}
         */
        createUrl (url, options) {
            let path, search;
            if (!options.url) throw new Error(`options.url is not find!`);
            if (url.startsWith('http')) {
                return url
            }

            path = url.trim();

            // console.log('CreateUrl.url: => ', url, options);

            const notSearch = path.indexOf('?') < 0;
            if (notSearch) {
                let index = path.lastIndexOf('/');
                let length = path.length;

                if (index === length - 1) {
                    path = path.substring(0, index)
                }
            } else {
                [ path, search ] = url.trim().split('?');
                // search = this._search(search, options.params);
                search = this.search(options.params);
            }

            path = this.template(path, options.path);

            if (search) {
                if (path.indexOf('?') > -1) {
                    path = `${path}&${search}`
                } else {
                    path = `${path}?${search}`
                }
            }

            if (path.startsWith('/')) {
                path = path.substring(1, path.length)
            }

            // console.log(`${ origin }/${ path }`);
            return `${ origin }/${ path }`
        },

        /**
         * 讲字符串模板，转换为 url 路径
         * template("/path/{  page  }/{size}", {page: 12, size: 20}) => /page/12/20
         * @param str
         * @param obj
         */
        template(str, obj) {
            return str.replace(/\{(\s*\w+\s*)\}/g, (match, string) => {
                const value = obj[string.trim()];
                if (!value) throw new Error(`url path "${match}" is not find!`);
                return value
            })
        },

        /**
         * search("page=&size=", {page: 1, size: 2}) => "page=1&size=2"
         * @param search
         * @param options
         * @returns {string}
         */
        _search(search, options = {}) {
            if (!search) return;
            return search.replace(/(\w+)=/g, (match, string) => {
                return match + (options[string.trim()] ? options[string.trim()] : '')
            })
        },

        /**
         * search({page: 1, size: 2}) => "page=1&size=2"
         * @param options
         * @returns {string}
         */
        search(options = {}) {
            return Object.entries(options).map(item => item.join('=')).join('&')
        },

        createHeaders(headers) {
            const token = util.getStorage("auth_token");
            const _headers = {};

            if (token) {
                _headers.authorization = token
            }

            if (typeof headers === 'function') {
                Object.assign(_headers, headers());
            }

            if (typeof headers === 'object') {
                Object.assign(_headers, headers);
            }

            return _headers
        }
    });

    return new CreateUrl()
});


